package faceattendsystem.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import faceattendsystem.entity.Specday;
import faceattendsystem.service.ISpecdayService;
import faceattendsystem.serviceImpl.SpecdayServiceImpl;
import net.sf.json.JSONObject;

public class AddSpecdayServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ISpecdayService specdayService = new SpecdayServiceImpl();
		
		Map<String,String> errors = new HashMap<String,String>();
		String spectype = req.getParameter("spectype");
		String specname = req.getParameter("specname");
		if(!specname.isEmpty()){
			if (!specname.matches("[\u4e00-\u9fa5]+")) {
				errors.put("specname", "节假名须是常见汉字!");
			} else if (specname.length() > 10) {
				errors.put("specname", "节假名长度不能超过10个汉字!");
			}
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String specbdate = req.getParameter("specbdate");
		String specedate = req.getParameter("specedate");
		if(specbdate.compareTo(specedate)>0){
			errors.put("specedate", "结束日期不能比开始日期早!");
		}
		
		Date bdate = null,edate = null;
		try {
			bdate = new Date(sdf.parse(specbdate).getTime());
		} catch (ParseException e) {
			errors.put("specbdate", "开始日期错误!");
		}
		
		int result = specdayService.isRepeatDate(bdate);
		if(result!=0){
			errors.put("specbdate", "日期已被覆盖!");
		}
		
		try {
			edate = new Date(sdf.parse(specedate).getTime());
		} catch (ParseException e) {
			errors.put("specedate", "结束日期错误!");
		}
		
		if(errors.size()!=0){
			errors.put("flag", "1");
		}else{
			errors.put("flag", "0");
			Specday specday = new Specday();
			specday.setSpecbdate(bdate);
			specday.setSpecedate(edate);
			specday.setSpecname(specname);
			specday.setDaytype(spectype);
			specdayService.add(specday);
		}
		JSONObject json = JSONObject.fromObject(errors);// 使用JSONobject将map对象转换成json对象
		PrintWriter out = resp.getWriter();
		out.print(json);
	}
}
